package scmd.team.noone.weatherlivewallpaper.serviceforecast;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class GetWeatherInfo {
	public static final String API_KEY = "c19c20685e011517121904";
	public static final String SERVICE_URL = "http://free.worldweatheronline.com/feed/weather.ashx?format=xml";
	private String cityName = "Hanoi";
	private String urlRequest;

	public String getUrlRequest() {
		return urlRequest;
	}

	public String getCityName() {
		return cityName;
	}

	public void setCityName(String cityname) {
		this.cityName = cityname;
	}

	public GetWeatherInfo() {
		urlRequest = SERVICE_URL + "&q=" + cityName + "&key=" + API_KEY + "&num_of_days=" + WeatherInfo.MAX_DAY;
	}

	public static WeatherInfo ReadWeatherInfo(String xml) {
		WeatherInfo wInfo = new WeatherInfo();

		Document doc = XMLfromString(xml);

		if (doc != null) {
			String[] temp = new String[WeatherInfo.MAX_DAY];
			wInfo.cityName = doc.getElementsByTagName("query")
					.item(0).getTextContent();
			wInfo.setTempC(doc.getElementsByTagName("temp_C").item(0).getTextContent());
			wInfo.setTempF(doc.getElementsByTagName("temp_F").item(0).getTextContent());
			for (int i = 0; i < WeatherInfo.MAX_DAY; i++) {
				temp[i] = doc.getElementsByTagName("tempMaxC").item(i).getTextContent();
			}
			wInfo.setTempMax(temp);
			for (int i = 0; i < WeatherInfo.MAX_DAY; i++) {
				temp[i] = doc.getElementsByTagName("tempMinC").item(i).getTextContent();
			}
			wInfo.setTempMin(temp);
			wInfo.weatherCode = doc.getElementsByTagName("weatherCode").item(0).getTextContent();
		}
		return wInfo;
	}

	public static Document XMLfromString(String xml) {

		Document doc = null;

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			doc = db.parse(is);

		} catch (ParserConfigurationException e) {
			return null;
		} catch (SAXException e) {
			return null;
		} catch (IOException e) {
			return null;
		}

		return doc;

	}

}
